package com.example.gaojt.androiddemo.statical.sdk;

import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

public class StatisticsUtils {
    // 2.0统计
    public static final String STATISTICAL_VERSION = "2.0";
    private static final String KEY_APP_KEY = "appkey";
    private static final String KEY_STATISTICAL_VERSION = "SV";
    private static final String KEY_STATISTICAL_COMMON = "COMMON";
    private static final String KEY_STATISTICAL_EVENT = "EV";

    public static HashMap<String, String> getMap() {
        HashMap<String, String> params = new HashMap<>();
        return params;
    }

    /**
     * @param event
     * @return
     */
    public static String convertEventItem2Json(EventItem event, StatisticsApi.Config config) {
        if (event == null) throw new RuntimeException("error!event item can not be null");
        JSONObject root = new JSONObject();
        try {
            JSONObject commonJsonObject = new JSONObject();
            JSONObject eventJsonObject = new JSONObject();
            CommonParams commonParams = event.getCommonParams();
            Map<String, String> commonMap = CommonParams.convertCommonParam2Map(commonParams);
            commonJsonObject.put("COMMONARRAY", convertEventMap2JsonArray(commonMap));
            eventJsonObject.put("ET", event.getStartTime());
            eventJsonObject.put("EN", event.getEventName());
            eventJsonObject.put("ETYPE", event.getEventType());
            String json = null;
            Map<String, String> eventMap = event.getEventParamMap();
            if (eventMap != null) {
                json = convertEventMap2JsonArray(eventMap).toString();
            }
            if (!TextUtils.isEmpty(json)) {
                JSONArray jsonArray = new JSONArray(json);
                eventJsonObject.put("i", jsonArray);
            }
            root.put(KEY_APP_KEY, config.appKey);
            root.put(KEY_STATISTICAL_VERSION, STATISTICAL_VERSION);
            root.put(KEY_STATISTICAL_COMMON, commonJsonObject);
            root.put(KEY_STATISTICAL_EVENT, eventJsonObject);
            return root.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            return "";

        }

    }

    private static JSONArray convertEventMap2JsonArray(Map<String, String> eventMap) {
        JSONArray jsonArray = new JSONArray();
        for (Map.Entry<String, String> entry : eventMap.entrySet()) {
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("k", entry.getKey());
                jsonObject.put("v", entry.getValue());
                jsonArray.put(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return jsonArray;
    }

    // 获取系统版本
    public static String getOsVersionName() {
        return Build.VERSION.RELEASE;
    }

    // 获取系统版本
    public static int getOsSDKINT() {
        return Build.VERSION.SDK_INT;
    }

    public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info == null || !info.isAvailable()) {
                return false;
            }
            return true;
        } catch (Throwable e) {
            return false;
        }
    }

    public static String getMacAddress() {
        String macAddress = "";
        String str;
        LineNumberReader input = null;
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            input = new LineNumberReader(ir);
            if ((str = input.readLine()) != null) {
                macAddress = str.trim(); // 去空格
            }
        } catch (IOException ex) {
            ex.printStackTrace();

        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null == macAddress ? "" : macAddress;
    }


    public static String getAndroidId(Context context) {
        String androidId = null;
        if (context != null) {
            androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        }
        return null == androidId ? "" : androidId;
    }

    public static String getCUReference() {
        try {
            Class<?> systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method getMethod = systemPropertiesClass.getMethod("get", String.class);
            Object obj = getMethod.invoke(null, "ro.tct.curef");
            return obj == null ? "" : (String) obj;
        } catch (Exception e) {
            return "";
        }
    }

    public static String getDeviceName() {
        return Build.MODEL;
    }

    public static String getSystemVersionCode() {
        return Build.VERSION.RELEASE;
    }

    public static String getSystemVersionName() {
        return Integer.toString(Build.VERSION.SDK_INT);
    }

    public static String getImei1(Context context) {
        return "";
    }

    public static String getImei2(Context context) {
        return "";
    }

    public static String getImsi1(Context context) {
        return "";
    }

    public static String getImsi2(Context context) {
        return "";
    }

    public static String getNetwork() {
        return "";
    }

    public static String getLanguage() {
        return "";
    }

    public static String getRamSize() {
        return "";
    }

    public static String getRomSize() {
        return "";
    }

    public static String getScreenWH() {
        return "";
    }

    public static String getPhoneSize() {
        return "";
    }

    public static String getIsRoot() {
        File f = null;
        final String kSuSearchPaths[] = {"/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/"};
        try {
            for (int i = 0; i < kSuSearchPaths.length; i++) {
                f = new File(kSuSearchPaths[i] + "su");
                if (f != null && f.exists()) {
                    return "true";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "false";
    }

    public static String getMMC() {
        return "";
    }

    /**
     * 阿拉伯语中String.format的时候，会将数字转化成阿拉伯语 为什么呢？Android阿拉伯文机子中时间日期本地语言中没有0-9，设置语言无效
     * <p/>
     * yyyy-MM-DD hh:mm:ss
     *
     * @param time
     * @return
     */
    public static String getTime2GMT(long time) {
        StringBuffer sb = new StringBuffer();
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"), Locale.US);
        if (time > 0) {
            calendar.setTimeInMillis(time);
        }


        sb.append(calendar.get(Calendar.YEAR));
        sb.append("-");
        if (calendar.get(Calendar.MONTH) + 1 < 10) {
            sb.append(0); // 补零
        }
        sb.append(calendar.get(Calendar.MONTH) + 1);
        sb.append("-");
        if (calendar.get(Calendar.DAY_OF_MONTH) < 10) {
            sb.append(0); // 补零
        }
        sb.append(calendar.get(Calendar.DAY_OF_MONTH));
        sb.append(" ");
        if (calendar.get(Calendar.HOUR_OF_DAY) < 10) {
            sb.append(0); // 补零
        }
        sb.append(calendar.get(Calendar.HOUR_OF_DAY));
        sb.append(":");
        if (calendar.get(Calendar.MINUTE) < 10) {
            sb.append(0); // 补零
        }
        sb.append(calendar.get(Calendar.MINUTE));
        sb.append(":");
        if (calendar.get(Calendar.SECOND) < 10) {
            sb.append(0); // 补零
        }
        sb.append(calendar.get(Calendar.SECOND));

        return sb.toString();
    }

    public static String getTimeZone() {
        try {
            TimeZone tz = TimeZone.getDefault();
            String s = tz.getDisplayName(false, TimeZone.SHORT) + " " + tz.getID();
            return s;
        } catch (Throwable e) {
            return null;
        }
    }

    public static String getTime2GMT() {
        return getTime2GMT(0);
    }


    // 网络状态
    public static final String UNKNWON = "unkwon";
    public static final String NOT_AVAILABLE = "not_avaible";
    public static final String WIFI = "wifi";
    public static final String G3NET = "3gnet";
    public static final String G3WAP = "3gwap";
    public static final String UNINET = "uninet";
    public static final String UNIWAP = "uniwap";
    public static final String CMNET = "cmnet";
    public static final String CMWAP = "cmwap";
    public static final String CTNET = "ctnet";
    public static final String CTWAP = "ctwap";
    public static final String MOBILE = "mobile";

    /**
     * 获取网络信息
     */
    public static String getNetStatus(Context context) {
        if (context.checkCallingOrSelfPermission(
                "android.permission.ACCESS_NETWORK_STATE") == PackageManager.PERMISSION_DENIED) {
            return UNKNWON;
        }
        try {
            ConnectivityManager connectivitymanager =
                    (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
            if (networkinfo == null || !networkinfo.isAvailable()) {
                return NOT_AVAILABLE;
            }

            if (networkinfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return WIFI;
            }
            String netInfo = networkinfo.getExtraInfo();
            if (netInfo == null) {
                return UNKNWON;
            }
            netInfo = netInfo.toLowerCase();
            if (netInfo.equals("cmnet")) {
                return CMNET;
            } else if (netInfo.equals("cmwap")) {
                return CMWAP;
            } else if (netInfo.equals("3gnet")) {
                return G3NET;
            } else if (netInfo.equals("3gwap")) {
                return G3WAP;
            } else if (netInfo.equals("uninet")) {
                return UNINET;
            } else if (netInfo.equals("uniwap")) {
                return UNIWAP;
            } else if (netInfo.equals("ctnet")) {
                return CTNET;
            } else if (netInfo.equals("ctwap")) {
                return CTWAP;
            } else {
                return MOBILE;
            }
        } catch (Throwable e) {
            return NOT_AVAILABLE;
        }
    }

}
